﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SY.BasicData.Api.Write.Basic.Applications.Command;
using SY.BasicData.Domain.Basic;
using SY.BasicData.Domain.DeepProcessing;
using SY.BasicData.ErrorCode;
using SY.BasicData.Infrastructures;

namespace SY.BasicData.Api.Write.Basic.Applications.CommandHandler
{
    public class AddBasicCommandHandler : IRequestHandler<AddBasicCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<BasicModel> basicRepository;
        private readonly IBaseRepository<DeepProcessingModel> deepprocessRepository;
        private readonly IMapper mapper;

        public AddBasicCommandHandler(IBaseRepository<BasicModel> basicRepository, IBaseRepository<DeepProcessingModel> deepprocessRepository, IMapper mapper)
        {
            this.basicRepository = basicRepository;
            this.deepprocessRepository = deepprocessRepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddBasicCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var batchExists = await basicRepository.GetAll().AnyAsync(c => c.Batch == request.Batch && !c.IsDeleted);
            if (batchExists)
            {
                result.Message = "生产批次不能重复";
                result.Code = ApiEnum.Fail;
                return result;
            }
            if (!string.IsNullOrEmpty(request.License))
            {
                var deepProcessCompany = await deepprocessRepository.GetAll().FirstOrDefaultAsync(c => c.Batch == request.Batch && !c.IsDeleted);

                if (deepProcessCompany != null && string.IsNullOrEmpty(deepProcessCompany.Leader))
                {
                    // 将基础信息的 License 赋值给深加工企业的 LicenseNum
                    deepProcessCompany.Leader = request.License;
                    await deepprocessRepository.Update(deepProcessCompany);
                }
            }
            //添加基础信息
            var model = mapper.Map<BasicModel>(request)
;
            model.Creator = request.Creator;
            model.CreatorDate = DateTime.Now;
            result.Data = await basicRepository.Add(model);
            result.Code = result.Data > 0 ? ApiEnum.Success : ApiEnum.Fail;
            result.Message = result.Data > 0 ? "添加基本信息成功" : "添加基本信息失败";
            return await Task.FromResult(result);

        }
    }
}
